﻿using System;
using System.Collections.Generic;
using System.Text;

using YouHP.Utility;
using YouHP.BLL;
using YouHP.Model;

namespace YouHP.Pages
{
    public class Login : BasePage
    {
        protected string postusername = "";
        protected string username;
        protected override void ShowPage()
        {
            base.ShowPage();

            this.SeoHead = "登录";

            if (IsPost) //处理登陆请求
            {
                HandleLogin();
            }
            else
            {
               username = CookiesTools.GetCookie("youhpPreUser");


                if ((RequestTools.GetUrlReferrer() == "") || (RequestTools.GetUrlReferrer().IndexOf("login") > -1) ||
                    RequestTools.GetUrlReferrer().IndexOf("logout") > -1)
                {
                    CookiesTools.SetPreUrl("index.aspx");
                }
                else
                {
                    CookiesTools.SetPreUrl(RequestTools.GetUrlReferrer());
                }
            }
        }

        private void HandleLogin()
        {
            bool loginsucc = false;
            string userName = RequestTools.GetFormString("username");
            string password = Utils.MD5(RequestTools.GetFormString("password"), 16);
            int expireTime = RequestTools.GetFormInt("expiretime",-1);

            try
            {
                UserInfo user = UserBLL.Instance.CheckUserLogin(userName, password);
                if (user == null)
                {
                    this.AddErrLine("登录失败,用户名或密码错误！");
                    return;
                }
                else if (user.IsActive != 1)
                {
                    this.AddErrLine("您的帐号还没有激活，请激活后再登录");
                    return;
                }
                else 
                {
                    UserData.Id = user.Id;
                    UserData.UserTypeId = user.UserTypeId;
                    UserData.UserName = userName;

                    //写cookie
                    //if (expireTime <= 0) expireTime = -1;
                    CookiesTools.WriteUserCookie(UserData.Id.ToString(), UserData.UserName, expireTime);
                    //CookiesTools.WriteUserNameCookie(UserData.UserName);    //将本次登陆的用户名写入cookie，方便下次用户的输入

                    //提示登陆成功，并根据用户类型以及上一个要求登陆的页面来决定转向的url
                    this.AddMsgLine("登录成功");
                    string nextUrl = CookiesTools.GetPreUrl();
                    this.SetUrl(nextUrl);
                    this.SetMetaRefresh(3, nextUrl);

                    loginsucc = true;
                }
            }
            catch(Exception e)
            {
                this.AddErrLine(e.ToString());
            }

            if (loginsucc == false)
            {
                this.AddErrLine("登录失败,用户名或密码错误！");
            }
        }
    }
}
